//dic模块名，内部方法调用使用模块名，更改模块名会出错
//缓存存储数据字典，从服务器获取
import $http from "@/static/js/http.js"
import $api from "@/static/js/api.js"

// initial state
const state = () => ({
	dataTimeout: 3600000 *24,//一天
	data:{
		// dicName:{
		// 	key:value,
		// 	Symbol("lastTime"):"" //非Symbol可枚举属性才能写入缓存(坑)
		// }
	}
})

// mutations，内部无法return向外传值
const mutations = {
	refreshDic(state, obj){
		try {
		    let dic = uni.getStorageSync("dic_" + obj.key);
			state.data[obj.key] = dic.content;
		} catch (e) {
		    console.error(`字典${obj.key}刷新失败`);
		}
	},
	setTemporaryDic(state, obj){
		try{
			for(let item of obj){
				state.data[item.key] = item.data;
			}
		} catch (e) {
		    console.error(`临时字典写入失败`);
			console.log(obj);
		}
	}
}

// actions
const actions = {
	getDics({ commit, state },obj){
		let keys = $api.strToArr(obj.key, ",");//可为逗号分隔的多个组合
		console.log("申请字典：", keys);
		let check = true;
		let now = Date.now();
		for(let item of keys){
			let dic = uni.getStorageSync("dic_" + item);
			//只要有一个字典未找到或已过期，重新下载keys内指定字典，一次请求
			if(!dic || now - dic.lastTime > state.dataTimeout){
				console.log("校验错误字典", item, dic);
				check = false;
				break;
			}
		}
		if(!check || obj.force){//字典未找到、超时或强制刷新
			console.log("字典未下载，开始请求");
			return $http.uquest({
				url:"dic",
				data:{
					dicMapNames: keys.toString(),
				},
			}).then((res)=>{
				// console.log("字典数据：");
				// console.log(res);
				let dics = res.data;
				// console.log(dics);
				try{
					for(let key of Object.keys(dics)){
						uni.setStorageSync("dic_" + key, {
							content: dics[key],
							lastTime: now
						});
						commit('refreshDic',{key:key});
					}
					if(obj.success){
						obj.success();
					}
				}catch(e){
					console.error(`字典${obj.key}存储失败`, e);
					if(obj.fail){
						obj.fail();
					}
				}
			}).finally(()=>{
				if(obj.complete){
					obj.complete();
				}
			})
		}else{//字典已存在，从缓存读取到临时状态
			console.log("字典已下载，载入");
			for(let key of keys){
				commit('refreshDic',{key:key});
			}
			if(obj.success){
				obj.success();
			}
			if(obj.complete){
				obj.complete();
			}
			return Promise.resolve()
		}
	},
	setDics({ commit },arrObj){
		// 数据格式:
		// [
		// 	{
		// 		key:字典名,
		// 		data:字典数组
		// 	}
		// ]
		commit('setTemporaryDic',arrObj);
	}
}

// getters
const getters = {}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}
